package edu.uic.readfile;

import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Vector;

public class KNN
{

	private TrainingData trainingdata;
	private TestFile testfile;
	private int K = 5;
	private TreeMap<Double, SingleFile> distanceMap = new TreeMap();
	private Vector<String> knnSet = new Vector<String>();
	
	
	public KNN()
	{
		trainingdata = new TrainingData();
		
		trainingdata.isC = false;
		trainingdata.wordset.readfromFile();
		trainingdata.transferFile("articles/l");
		trainingdata.isC = true;
		trainingdata.transferFile("articles/c");
		
		testfile = new TestFile("articles/L.txt", trainingdata);
	}
	
	
	public void getKNN()
	{
		for(SingleFile sfile : trainingdata.fileset.trainingSet)
		{
			double dist = distance(sfile.normalVector, testfile.testFile.normalVector);
			distanceMap.put(dist, sfile);
		}
		
		int i = 0;
		double testvalue = 0.0;
		for(double dist : distanceMap.keySet())
		{
			System.out.println(distanceMap.get(dist).fileName + " " + dist);
			if(i < K)
			{
				testvalue += distanceMap.get(dist).value;
				knnSet.add(distanceMap.get(dist).fileName);
				++i;
			}
			else
				break;
		}
		
		testfile.value = testvalue;
	}
	
	public void output()
	{
		System.out.println("the test file is ");
		if(testfile.value > 0)
			System.out.println("Conservative");
		else
			System.out.println("Liberal");
		
		for(String filename : knnSet)
		{
			System.out.println(filename);
		}
	}
	
	public double distance(ArrayList<Double> a, ArrayList<Double> b)
	{
		double d = 0;
		double ab = 0;
		double a2 = 0;
		double b2 = 0;

		if (a.size() != b.size())
		{
			System.out.println("not the same size");
			System.out.println(b.size());
			System.exit(1);
		}

		int size = a.size();
		for (int i = 0; i < size; i++)
		{

			ab += a.get(i).doubleValue() * b.get(i).doubleValue();
			a2 += Math.pow((Double) a.get(i).doubleValue(), 2);
			b2 += Math.pow((Double) b.get(i).doubleValue(), 2);
		}

		d = ab / (Math.sqrt(a2) * Math.sqrt(b2));
		return d;
	}
	
	public static void main(String[] args)
	{
		KNN knn = new KNN();
		knn.getKNN();
		knn.output();
	}
	
	
}
